package logic

import (
	"baidu-dev/api/internal/svc"
	"baidu-dev/api/internal/types"
	"context"
	"net/http"
	"path/filepath"

	"github.com/zeromicro/go-zero/core/logx"
	"golang.org/x/text/cmd/gotext/examples/extract_http/pkg"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line

	file, m, err := req.FormFile("Image")
	if err != nil {
		return &types.Response{
			Message: err.Error(),
			Data:    nil,
			Code:    500,
		}, nil
	}


	ext:=filepath.Ext(m.Filename)
	if ext!=".png"&&ext!=".jpg"{
		return &types.Response{
			Message: "图片上传格式只能为png和jpg",
			Data:    nil,
			Code:    500,
		}, nil
	}

	if m.Size>1024*1024*5{
		return &types.Response{
			Message: "图片上传大小不能超过5M",
			Data:    nil,
			Code:    500,
		}, nil
	}


	upload,_:=pkg.Upload(file,m){
		if err != nil {
			return &types.Response{
				Message: "success",
				Data:    nil,
				Code:    200,
			}, nil
		}
	}

	return &types.Response{
		Message: "success",
		Data:    upload,
		Code:    200,
	}, nil
}
